package com.xbl.mail.service;

import com.xbl.mail.config.database.ReadOnlyConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.xbl.mail.emumeration.MailStatus;
import com.xbl.mail.emumeration.RedisPriorityQueue;
import com.xbl.mail.entity.MailSend;
import com.xbl.mail.mapper.MailSend1Mapper;
import com.xbl.mail.mapper.MailSend2Mapper;
import com.xbl.mail.utils.FastJsonConvertUtil;

import java.util.ArrayList;
import java.util.List;

@Service
public class MailSendService {
	private static Logger LOGGER = LoggerFactory.getLogger(MailSendService.class);

	@Autowired
	private MailSend1Mapper mailSend1Mapper;

	@Autowired
	private MailSend2Mapper mailSend2Mapper;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	public void insert(MailSend mailSend) throws Exception {
		int hashCode = mailSend.getSendId().hashCode();
		if (hashCode % 2 == 0) {
			mailSend2Mapper.insert(mailSend);
		} else {
			mailSend1Mapper.insert(mailSend);
		}
	}

	/**
	 * 把mailsend放到redis的队列中
	 * 
	 * @param mailSend
	 */
	public void sendRedis(MailSend mailSend) {
		
		int hashCode = mailSend.getSendId().hashCode();
		if(hashCode % 2 == 0){
			mailSend = mailSend2Mapper.selectByPrimaryKey(mailSend.getSendId());
		} else {
			mailSend = mailSend1Mapper.selectByPrimaryKey(mailSend.getSendId());
		}
		
		ListOperations<String, String> opsForList = redisTemplate.opsForList();
		// 获取优先级
		Long priority = mailSend.getSendPriority();
		Long ret = 0L;
		Long size = 0L;
		if (priority < 4L) {
			// 进入延迟的队列1、2、3
			// 返回扫结果是最新的容器长度
			ret = opsForList.rightPush(RedisPriorityQueue.DEFER_QUEUE.getCode(), FastJsonConvertUtil.convertObjectToJSON(mailSend));
			// 获取当前最新的容器长度
			size = opsForList.size(RedisPriorityQueue.DEFER_QUEUE.getCode());
		} else if (priority < 7L) {
			// 进入普通的队列4、5、6
			ret = opsForList.rightPush(RedisPriorityQueue.NORMAL_QUEUE.getCode(), FastJsonConvertUtil.convertObjectToJSON(mailSend));
			size = opsForList.size(RedisPriorityQueue.NORMAL_QUEUE.getCode());
		} else {
			// 进入紧急队列7、8、9
			ret = opsForList.rightPush(RedisPriorityQueue.FAST_QUEUE.getCode(), FastJsonConvertUtil.convertObjectToJSON(mailSend));
			size = opsForList.size(RedisPriorityQueue.FAST_QUEUE.getCode());
		}
		// 只要投递了，投递次数+1
		mailSend.setSendCount(mailSend.getSendCount() + 1);
		// 投递成功
		if (ret == size) {
			// 设置投递成功的状态
			mailSend.setSendStatus(MailStatus.SEND_IN.getCode());
			if (mailSend.getSendId().hashCode() % 2 == 0) {
				mailSend2Mapper.updateByPrimaryKeySelective(mailSend);
			} else {
				mailSend1Mapper.updateByPrimaryKeySelective(mailSend);
			}
			LOGGER.info("-------进入redis队列成功,ID:{}-------", mailSend.getSendId());
		}
		// 投递失败
		else {
			if (mailSend.getSendId().hashCode() % 2 == 0) {
				mailSend2Mapper.updateByPrimaryKeySelective(mailSend);
			} else {
				mailSend1Mapper.updateByPrimaryKeySelective(mailSend);
			}
			LOGGER.info("-------进入redis队列失败,等待下次轮循重新投递ID:{}-------", mailSend.getSendId());
		}

	}

	@ReadOnlyConnection
	public List<MailSend> queryDraftList() {
		List<MailSend> list = new ArrayList<MailSend>();
        list.addAll(mailSend1Mapper.queryDraftList());
        list.addAll(mailSend2Mapper.queryDraftList());
		return list;
	}
}
